package com.lkd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lkd.constant.JwtConstants;
import com.lkd.mapper.UserMapper;
import com.lkd.domain.User;
import com.lkd.pageParam.UserPageParam;
import com.lkd.pojo.dto.LoginDto;
import com.lkd.pojo.vo.LoginUserVo;
import com.lkd.properties.JwtProperties;
import com.lkd.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lkd.utils.EmptyUtil;
import com.lkd.utils.JwtUtil;
import com.lkd.utils.UserThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author author
 * @since 2025-02-12
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    JwtProperties jwtProperties;
    @Override
    public Page<User> search(UserPageParam param) {
        Page<User> page = new Page<>(param.getPageIndex(),param.getPageSize());
        List<User> userList = userMapper.search(param.getUserName());
        page.setTotal(userList.size()).setRecords(userList);
        return page;
    }
    @Override
    public LoginUserVo login(LoginDto dto) {

        if(EmptyUtil.isNullOrEmpty(dto)){
            //参数异常
        }

        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getLoginName,dto.getLoginName());
        User user = userMapper.selectOne(wrapper);

        if(user == null){ //代表用户不存在得

        }
        if(!user.getPassword().equals(dto.getPassword())){ //代表密码错误

        }
        //密码相等
        LoginUserVo loginUserVo = new LoginUserVo();
        loginUserVo.setUserId(user.getId());
        loginUserVo.setUserName(user.getUserName());
        loginUserVo.setRoleCode(user.getRoleCode());
        loginUserVo.setSuccess(true);
        loginUserVo.setMsg("登录成功");
        //将用户id等信息存入threadLocal中
        Map<String,Object> claims = new HashMap<>();
        claims.put("user", JwtConstants.USER_ID);
        String jwt = JwtUtil.createJWT(jwtProperties.getBase64EncodedSecretKey()
                , Integer.parseInt(jwtProperties.getTtl()), claims);
        UserThreadLocal.setSubject(jwt);
        //获取当前用户的所有资源列表
        //1.获取白名单资源
        //2.获取用户角色资源列表，从redis中获取
        //3.合并
        loginUserVo.setToken(UUID.randomUUID().toString());
        return loginUserVo;
    }
}
